<?php

namespace app\admin\controller\shop;

use app\admin\model\goods\GoodsCategoryModel;
use app\admin\model\goods\GoodsModel;
use app\admin\model\shop\ShopGoodsCategoryModel;
use app\admin\model\shop\ShopGoodsModel;
use app\admin\model\shop\ShopGoodsStockLogModel;
use app\api\controller\User;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * Merchant Profile
 *
 * @icon fa fa-circle-o
 */
class Message extends Backend
{

    /**
     * Message模型对象
     * @var \app\admin\model\shop\Message
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Message;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $shop_where = [];
        $shop_ids = getShopIds($this->auth->id);
        if ($shop_ids != '*') {
            $shop_where['id'] = ['in', $shop_ids];
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where($shop_where)
            ->order($sort, $order)
            ->paginate($limit);


        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            //生成二维码
            $qrcode = $this->qrcode(1);
            $this->model->where(['id' => $this->model->id])->update(['qrcode' => $qrcode]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * @ApiInternal
     * 生成二维码
     */
    public function qrcode($user_id)
    {
        $result = \Endroid\QrCode\Builder\Builder::create()
            ->writer(new \Endroid\QrCode\Writer\PngWriter())
            ->writerOptions([])
            ->data($user_id)
            ->encoding(new \Endroid\QrCode\Encoding\Encoding('UTF-8'))
            // ->errorCorrectionLevel(new \Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            // ->roundBlockSizeMode(new \Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin())

            //// 设置二维码 LOGO 图片
            // ->logoPath(__DIR__.'/icon.png')

            //// 设置二维码标签字段
            // ->labelText('This is the label')
            // ->labelFont(new \Endroid\QrCode\Label\Font\OpenSans(20))
            // ->labelAlignment(new \Endroid\QrCode\Label\Alignment\LabelAlignmentCenter())
            ->validateResult(false)
            ->build();

        // 输出 Base64 图片
        $base64Image = $result->getDataUri();

        // 解码Base64数据
        $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64Image));

        // 生成文件名
        $fileName = time() . '.png';
        // 保存文件到指定路径
        $filePath = ROOT_PATH . 'public/uploads/qrcode' . $fileName;
        file_put_contents($filePath, $imageData);
        return '/uploads/qrcode' . $fileName;
    }


    public function goods($ids = null)
    {


        $this->assignconfig('shop_id', $ids);
        return $this->view->fetch();
    }

    /**
     * Notes: 查询商品分类
     * User: AerYYY
     * Date: 6/28/25
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function category()
    {

        $this->model = new GoodsCategoryModel();
        if ($this->request->isAjax()) {

            $shop_id = input('shop_id');
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->field('id,name')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->field('id,name')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $shopCategoryIds = ShopGoodsCategoryModel::where('shop_id', $shop_id)
                ->column('goods_category_id');

            foreach ($list as &$item) {
                if (in_array($item['id'], $shopCategoryIds)) {
                    $item['have'] = 200;
                } else {
                    $item['have'] = 100;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }


    /**
     * Notes: 查询商品
     * User: AerYYY
     * Date: 6/28/25
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goods_list()
    {
        $this->model = new GoodsModel();
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $shop_id = input('shop_id');
            $shopGoodsModel = new ShopGoodsModel();
            $shopGoodsIds = $shopGoodsModel->where('shop_id', $shop_id)
                ->column('goods_id');

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();


            foreach ($list as &$item) {
                if (in_array($item['id'], $shopGoodsIds)) {
                    $item['have'] = 200;
                } else {
                    $item['have'] = 100;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
    }


    /**
     * Notes: 添加门店分类
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function update_shop_category()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');

        if (empty($ids)) {
            return json(['code' => 0, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 0, 'msg' => __('Shop id error')]);
        }

        $shopGoodsCategoryModel = new ShopGoodsCategoryModel();
        $old_category_ids = $shopGoodsCategoryModel->where('shop_id', $shop_id)->column('goods_category_id');

        $new_category_ids = array_diff($ids, $old_category_ids);

        if (empty($new_category_ids) || count($new_category_ids) <= 0) {
            return json(['code' => 0, 'msg' => 'success']);
        }

        $data = [];
        foreach ($new_category_ids as $v) {
            $data[] = [
                'shop_id' => $shop_id,
                'goods_category_id' => $v,
            ];
        }

        $shopGoodsCategoryModel->insertAll($data);

        return json(['code' => 0, 'msg' => 'success']);
    }


    /**
     * Notes: 添加门店商品
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function add_shop_goods()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');
        if (empty($ids)) {
            return json(['code' => 1, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 1, 'msg' => __('Shop id error')]);
        }

        $shopGoodsModel = new ShopGoodsModel();
        $res = $shopGoodsModel->add_shop_goods($ids, $shop_id);

        if ($res === false) {
            return json(['code' => 1, 'msg' => __($shopGoodsModel->getError())]);
        }

        return json(['code' => 0, 'msg' => 'success']);
    }


    /**
     * Notes: 删除门店商品
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function delete_shop_goods()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');
        if (empty($ids)) {
            return json(['code' => 1, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 1, 'msg' => __('Shop id error')]);
        }

        $shopGoodsModel = new ShopGoodsModel();
        $res = $shopGoodsModel->delete_shop_goods($ids, $shop_id, $this->auth->id);

        if ($res === false) {
            return json(['code' => 1, 'msg' => __($shopGoodsModel->getError())]);
        }

        return json(['code' => 0, 'msg' => 'success']);
    }


    /**
     * Notes: 库存页面管理
     * User: AerYYY
     * Date: 6/29/25
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function stock()
    {

        $this->model = new ShopGoodsModel();
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        $shop_where = [];
        $shop_ids = getShopIds($this->auth->id);
        if ($shop_ids != '*') {
            $shop_where['shop_goods_model.shop_id'] = ['in', $shop_ids];
        }

        $other_where = [];
        $filter = json_decode($this->request->get("filter"), true);
        $op = json_decode($this->request->get("op"), true);
        if (!empty($filter['category_id'])) {
            $other_where['goods.category_id'] = ['=',$filter['category_id']];
            unset($filter['category_id'], $op['category_id']);
        }
        $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->with(['shop', 'goods'])
            ->where($shop_where)
            ->where($other_where)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list->items() as &$item){
            $item['category_name'] = GoodsCategoryModel::where('id',$item['goods']['category_id'])
                ->value('name');
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);

    }


    /**
     * Notes: 编辑库存
     * User: AerYYY
     * Date: 6/29/25
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit_stock($ids = null)
    {
        $shopGoodsModel = new ShopGoodsModel();
        if ($this->request->isPost()) {
            $params = input('row/a');
            $params['number'] = (int)$params['number'];
            $params['price'] = (float)$params['price'];
            if($params['price'] <= 0){
                $this->error('The price of a good cannot be less than or equal to 0');
            }

            $info = $shopGoodsModel->where('id', $params['id'])->find();
            if (empty($info)) {
                $this->error('This information no longer exists');
            }


            $shopGoodsModel->startTrans();
            try {
                if (!empty($params['number'])) {
                    $log_data['shop_id'] = $info->shop_id;
                    $log_data['goods_id'] = $info->goods_id;
                    $log_data['before'] = $info->stock;
                    if ($params['number'] > 0) {
                        $info->stock = $info->stock + $params['number'];
                        $log_data['type'] = ShopGoodsStockLogModel::TYPE_IN;
                    } else {

                        if ($info->stock < abs($params['number'])) {
                            $this->error('The current inventory is insufficient for deduction');
                        }

                        $info->stock = $info->stock - abs($params['number']);
                        $log_data['type'] = ShopGoodsStockLogModel::TYPE_OUT;
                    }

                    $log_data['number'] = $params['number'];
                    $log_data['after'] = $info->stock;
                    $log_data['op_admin_id'] = $this->auth->id;
                    $log_data['createtime'] = time();
                    ShopGoodsStockLogModel::add($log_data);
                }
                $info->price = $params['price'];
                $info->save();
                $shopGoodsModel->commit();
            } catch (Exception $exception) {
                $shopGoodsModel->rollback();
                $this->error($exception->getMessage());
            }

            $this->success('success');

        }


        $info = $shopGoodsModel->where('id', $ids)->find();
        if (empty($info)) {
            $this->error('This information no longer exists');
        }

        $info['shop'] = $this->model->where('id', $info['shop_id'])->find();
        $info['goods'] = GoodsModel::where('id', $info['goods_id'])->find();

        $this->assign('info', $info);
        return $this->view->fetch();
    }
}
